<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2018 http://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------
namespace app\mpopen\controller;

use com\wxpay\WxPayApi;
use com\wxpay\database\WxPayNotify;
use com\wxpay\database\WxPayOrderQuery;
use app\common\model\ShopOrder;
use app\common\model\Order;
use app\common\model\ShopProduct;
use app\common\model\WxappUserTemplate;

class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->setTransactionId($transaction_id);
		$result = WxPayApi::orderQuery($input);

		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}
	
	//重写回调处理方法，成功的时候返回true，失败返回false，处理商城订单
	public function NotifyProcess($data, &$msg)
	{

		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}

        //以上的代码都是相同的，以下代码写定制业务逻辑，这里实现一个通用订单处理逻辑
        $order = model('order');
        //支付流水id是否已写入预支付订单表(order表)
        $orderHis = $order->where('trans_id',$data["transaction_id"])->find();
        if($orderHis){    //微信服务器会通知多次，如已写回就不再重复写了
            return true;
        }

        $transaction = model('transaction'); // 保存微信支付订单流水
        trace($data,'NotifyProcess');
        trace($msg,'NotifyProcessmsg');
        $transaction->data($data);
        $transaction->save();

        $map["out_trade_no"] = $data["out_trade_no"];
        $omap["order_id"] = $data["out_trade_no"];
        $data["paySta"] = 1;

        $order-> where($omap)->setField(["trans_id"=>$data["transaction_id"],'order_status'=>1]); //支付流水号写入订单
         //核销订单中使用的优惠券，核销逻辑并未提供完整演示，聪明的开发者请自己写 ：）
        $orderData = $order-> where($omap)-> find();
        trace($orderData,'NotifyProcess$order');
        if(empty($orderData->coupon)){               //订单没有使用优惠券

        }
        //根据订单一些特殊字段进行的后续处理
        switch ($orderData->addon) {
            //关注
            case 'home':
                break;
            case 'appstore':
                $asmap["id"] = $orderData->aim_id;
                $asorder = new ShopOrder();
                $asorder-> where($asmap)->setField(["payment_time"=>time(),"paid_info"=>json_encode($data),"status"=>1]); //应用市场订单处理
                //增加销量计数
                $asorderData = $asorder-> where($asmap)->find();
                trace($asorderData,'NotifyProcess$asorder');
                $asp = new ShopProduct();
                $asp->where('id',$asorderData->pro_id)->inc('sell_cnt')->update();
                //用户小程序模板表加入购买到的小程序模板数据
                $aspData = $asp->where('id',$asorderData->pro_id)->find();
                trace($aspData,'NotifyProcess$asorder$aspData');
                $utpl = new WxappUserTemplate();
                $utpl->mp_id = $asorderData->buyer_appletid;
                $uid = getUidByUserid($asorderData->user_id);
                trace($uid,'NotifyProcess$uid');
                $utpl->uid = $orderData->uid ? $orderData->uid : 0 ; //通用订单表中的uid也可能是空的，比如，用户在小程序购买商品时
                $utpl->product_id = $asorderData->pro_id;
                $utpl->template_id = $aspData->template_id;
                $utpl->ext_json = $aspData->ext_json;
                $utpl->user_version = "1";
                $utpl->user_desc = "";
                $utpl->status = 0;
                $utpl->audit_status = -1;
                $utpl->category_list = "";
                $utpl->page_list = "";
                $utpl->item_list = $aspData->item_list;
                $utpl->auditid = "";
                $utpl->reason = "";
                $utpl->save();

                break;
            default:

                break;
        }


            return true;
	}
}

